import Vue from 'vue';
import _Car from './car.vue';
export class Carousel{
  carousel = null;
  constructor(options) {
    this.self =  this;
    this.speed = options.speed;
    this.timer = null;
    this.curIndex = 0;
    this.runEvent = this.run.bind(this);
    this.init.apply(this);
    this.carItems = document.querySelectorAll('.car-item');
    this.indicatorItems = document.querySelectorAll('.indicator-item');
    this.autoPlay();
  }

  init() {
    let self = this;
    let carousel = Vue.extend(_Car);
    this.carousel = new carousel({
      data() {
        return {}
      },
      methods: {
        prev() {
          self._setIndex('prev');
          self._pageChange(self.curIndex);
        },
        next() {
          self._setIndex('next');
          self._pageChange(self.curIndex);
        },
      }
    }).$mount(document.createElement('div'));
    document.getElementById('homeView').appendChild(this.carousel.$el);
  }
  
  remove() {
    document.getElementById('homeView').removeChild(this.carousel.$el);
    this.carousel = null;
  }

  autoPlay () {
    this.timer = setInterval(this.runEvent, this.speed);
  }

  run () {
    this._setIndex('next')
    this._pageChange(this.curIndex);
  }

  _setIndex (dir) {
    switch (dir) {
      case 'next':
        this.curIndex === (this.carItems.length - 1) ? this.curIndex = 0 : this.curIndex ++;
        break;

      case 'prev':
        this.curIndex === 0 ? this.curIndex = (this.carItems.length - 1) : this.curIndex --;
        break;
    
      default:
        break;
    }
  }

  _pageChange (index) {
    let carItemsArr = Array.from(this.carItems);
    carItemsArr.map(item => {
      item.classList.remove('active');
    })
    this.carItems[index].classList.add('active');

    let indicatorItemsArr = Array.from(this.indicatorItems);
    indicatorItemsArr.map(item => {
      item.classList.remove('active');
    })
    this.indicatorItems[index].classList.add('active');
  }
}